package com.freedom.sql.jdbc.response;

import java.io.InputStream;
import java.net.Socket;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.freedom.sql.jdbc.request.SetNamesPacket;
import com.freedom.sql.jdbc.utils.BufferAllocateUtils;
import com.freedom.sql.jdbc.utils.ByteUtils;
import com.freedom.sql.jdbc.utils.LoggerUtils;

import io.netty.channel.socket.SocketChannel;

public class LoginOkPacket {

	private static final Logger logger = LogManager.getLogger(LoginOkPacket.class);
	private static final byte[] AUTH_OK_BYTES = new byte[] { 7, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0 };

	private SocketChannel channel;

	public LoginOkPacket(SocketChannel c) {
		channel = c;
	}

	public void write() {
		// 发送报文
		channel.writeAndFlush(BufferAllocateUtils.get(AUTH_OK_BYTES.length).writeBytes(AUTH_OK_BYTES));
	}

	// read
	private Socket socket;

	public LoginOkPacket(Socket _socket) {
		this.socket = _socket;
	}

	public void read() throws Exception {
		InputStream in = socket.getInputStream();
		// 1)3字节的heaerLength
		byte[] headerBytes = new byte[3];
		in.read(headerBytes, 0, 3);
		int headLength = ByteUtils.littleEndianInteger(headerBytes, 0, 3);
		LoggerUtils.debug(logger, "length : " + headLength);
		// 2) 1字节的packetNumber
		byte[] packetNumber = new byte[1];
		LoggerUtils.debug(logger, "try to read packetNumber");
		in.read(packetNumber, 0, 1);
		int packetSeq = ByteUtils.littleEndianInteger(packetNumber, 0, 1);
		LoggerUtils.debug(logger, "packet Num: " + packetSeq);
		// 3)一次性读取所有字节
		// 一次性读取所有字节
		byte[] allBytes = new byte[headLength];
		in.read(allBytes, 0, headLength);
		LoggerUtils.debug(logger, "all content is read done!");
		// 4)判断成功还是失败
		if (0 != allBytes[0]) {
			LoggerUtils.error(logger, "commons pool auth fail...");
			throw new Exception("commons pool auth fail...");
		}		
	}
}
